const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs').promises;
const { v4: uuidv4 } = require('uuid');
const { auth, checkUsageLimit } = require('../middleware/auth');
const { getConnection } = require('../config/database');

const router = express.Router();

// 确保上传目录存在
const uploadDir = process.env.UPLOAD_PATH || './uploads';
const ensureUploadDir = async () => {
  try {
    await fs.access(uploadDir);
  } catch {
    await fs.mkdir(uploadDir, { recursive: true });
  }
};

ensureUploadDir();

// 配置multer存储
const storage = multer.diskStorage({
  destination: async (req, file, cb) => {
    await ensureUploadDir();
    cb(null, uploadDir);
  },
  filename: (req, file, cb) => {
    const uniqueName = `${uuidv4()}-${Date.now()}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

// 文件过滤器
const fileFilter = (req, file, cb) => {
  const allowedImageTypes = ['image/jpeg', 'image/png', 'image/webp', 'image/bmp', 'image/tiff'];
  const allowedVideoTypes = ['video/mp4', 'video/avi', 'video/mov', 'video/wmv', 'video/mkv'];
  
  if (allowedImageTypes.includes(file.mimetype) || allowedVideoTypes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(new Error('不支持的文件类型'), false);
  }
};

// 创建multer实例
const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: parseInt(process.env.MAX_FILE_SIZE) || 20 * 1024 * 1024, // 20MB
    files: 10 // 最多10个文件
  }
});

// 单文件上传
router.post('/single', auth, checkUsageLimit, upload.single('file'), async (req, res) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: '请选择要上传的文件' });
    }

    const file = req.file;
    const connection = await getConnection();

    // 确定文件类型
    const isImage = ['image/jpeg', 'image/png', 'image/webp', 'image/bmp', 'image/tiff'].includes(file.mimetype);
    const taskType = isImage ? 'image' : 'video';

    // 创建任务记录
    const [result] = await connection.execute(
      'INSERT INTO tasks (user_id, task_type, original_file, status) VALUES (?, ?, ?, ?)',
      [req.user.id, taskType, file.filename, 'pending']
    );

    res.json({
      message: '文件上传成功',
      taskId: result.insertId,
      fileName: file.originalname,
      fileSize: file.size,
      fileType: taskType,
      uploadPath: `/uploads/${file.filename}`
    });
  } catch (error) {
    console.error('文件上传错误:', error);
    
    // 删除已上传的文件
    if (req.file) {
      try {
        await fs.unlink(req.file.path);
      } catch (unlinkError) {
        console.error('删除文件失败:', unlinkError);
      }
    }
    
    res.status(500).json({ error: '文件上传失败' });
  }
});

// 批量文件上传
router.post('/batch', auth, checkUsageLimit, upload.array('files', 10), async (req, res) => {
  try {
    if (!req.files || req.files.length === 0) {
      return res.status(400).json({ error: '请选择要上传的文件' });
    }

    const files = req.files;
    const connection = await getConnection();
    const tasks = [];

    for (const file of files) {
      const isImage = ['image/jpeg', 'image/png', 'image/webp', 'image/bmp', 'image/tiff'].includes(file.mimetype);
      const taskType = isImage ? 'image' : 'video';

      // 创建任务记录
      const [result] = await connection.execute(
        'INSERT INTO tasks (user_id, task_type, original_file, status) VALUES (?, ?, ?, ?)',
        [req.user.id, taskType, file.filename, 'pending']
      );

      tasks.push({
        taskId: result.insertId,
        fileName: file.originalname,
        fileSize: file.size,
        fileType: taskType,
        uploadPath: `/uploads/${file.filename}`
      });
    }

    res.json({
      message: '批量文件上传成功',
      tasks,
      totalFiles: files.length
    });
  } catch (error) {
    console.error('批量文件上传错误:', error);
    
    // 删除已上传的文件
    if (req.files) {
      for (const file of req.files) {
        try {
          await fs.unlink(file.path);
        } catch (unlinkError) {
          console.error('删除文件失败:', unlinkError);
        }
      }
    }
    
    res.status(500).json({ error: '批量文件上传失败' });
  }
});

// 获取上传进度
router.get('/progress/:taskId', auth, async (req, res) => {
  try {
    const { taskId } = req.params;
    const connection = await getConnection();

    const [tasks] = await connection.execute(
      'SELECT id, status, progress, error_message, created_at FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({ error: '任务不存在' });
    }

    res.json({
      taskId: tasks[0].id,
      status: tasks[0].status,
      progress: tasks[0].progress,
      errorMessage: tasks[0].error_message,
      createdAt: tasks[0].created_at
    });
  } catch (error) {
    console.error('获取进度错误:', error);
    res.status(500).json({ error: '获取进度失败' });
  }
});

// 删除文件
router.delete('/:taskId', auth, async (req, res) => {
  try {
    const { taskId } = req.params;
    const connection = await getConnection();

    // 获取任务信息
    const [tasks] = await connection.execute(
      'SELECT original_file, processed_file FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    if (tasks.length === 0) {
      return res.status(404).json({ error: '任务不存在' });
    }

    const task = tasks[0];

    // 删除文件
    try {
      if (task.original_file) {
        await fs.unlink(path.join(uploadDir, task.original_file));
      }
      if (task.processed_file) {
        await fs.unlink(path.join(uploadDir, task.processed_file));
      }
    } catch (fileError) {
      console.error('删除文件失败:', fileError);
    }

    // 删除数据库记录
    await connection.execute(
      'DELETE FROM tasks WHERE id = ? AND user_id = ?',
      [taskId, req.user.id]
    );

    res.json({ message: '文件删除成功' });
  } catch (error) {
    console.error('删除文件错误:', error);
    res.status(500).json({ error: '删除文件失败' });
  }
});

// 错误处理中间件
router.use((error, req, res, next) => {
  if (error instanceof multer.MulterError) {
    if (error.code === 'LIMIT_FILE_SIZE') {
      return res.status(400).json({ error: '文件大小超过限制' });
    }
    if (error.code === 'LIMIT_FILE_COUNT') {
      return res.status(400).json({ error: '文件数量超过限制' });
    }
    if (error.code === 'LIMIT_UNEXPECTED_FILE') {
      return res.status(400).json({ error: '意外的文件字段' });
    }
  }
  
  if (error.message === '不支持的文件类型') {
    return res.status(400).json({ error: '不支持的文件类型' });
  }
  
  console.error('上传错误:', error);
  res.status(500).json({ error: '文件上传失败' });
});

module.exports = router; 